package com.ruoyi.yljf.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.yljf.domain.vo.ClassifyVO;
import com.ruoyi.yljf.domain.vo.ClassifyVO2;
import com.ruoyi.yljf.domain.vo.ClassifyVO3;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yljf.mapper.ClassifyMapper;
import com.ruoyi.yljf.domain.Classify;
import com.ruoyi.yljf.service.IClassifyService;

import javax.annotation.Resource;

/**
 * 分类管理Service业务层处理
 * 
 * @author metaee
 * @date 2025-02-24
 */
@Service
public class ClassifyServiceImpl extends ServiceImpl<ClassifyMapper, Classify> implements IClassifyService {
    @Resource
    private ClassifyMapper classifyMapper;
    
    /**
     * 查询分类管理列表
     * 
     * @param classify 分类管理
     * @return 分类管理
     */
    @Override
    public List<Classify> selectClassifyList(Classify classify) {
    	LambdaQueryWrapper<Classify> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotEmpty(classify.getName())) {
			queryWrapper.like(Classify::getName, classify.getName());
		}
        if (StringUtils.isNotNull(classify.getParentId())) {
			queryWrapper.eq(Classify::getParentId, classify.getParentId());
		}
        return classifyMapper.selectList(queryWrapper);
    }

    @Override
    public List<ClassifyVO> queryClassifyList() {
        List<Classify> classifies = this.selectClassifyList(new Classify());
        Map<Long,List<Classify>> map = classifies.stream().collect(Collectors.groupingBy(Classify::getParentId));
        List<Classify> collect = map.getOrDefault(0L, new ArrayList<>());
        List<ClassifyVO> classifyVOS = BeanUtil.copyToList(collect, ClassifyVO.class);
        classifyVOS.forEach(vo1 -> {
            List<Classify> c2 = map.getOrDefault(vo1.getId(), new ArrayList<>());
            List<ClassifyVO2> classifyVOS2 = BeanUtil.copyToList(c2, ClassifyVO2.class);
            classifyVOS2.forEach(vo2 -> {
                List<Classify> c3 = map.getOrDefault(vo2.getId(), new ArrayList<>());
                List<ClassifyVO3> classifyVOS3 = BeanUtil.copyToList(c3, ClassifyVO3.class);
                vo2.setClassifyList(classifyVOS3);
            });
            vo1.setClassifyList(classifyVOS2);
        });
        return classifyVOS;
    }

    @Override
    public List<ClassifyVO> queryByParentId(Long parentId) {
        List<Classify> classifies = this.classifyMapper.selectList(
                new LambdaQueryWrapper<Classify>()
                        .eq(Classify::getParentId, parentId)
        );
        return classifies.stream().map(ClassifyVO::new).collect(Collectors.toList());
    }


}
